import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

///商品增减组件
class GoodsAddMinus extends StatefulWidget {
  ///商品数量
  final int num;

  ///减少商品数量回调
  final Function(int goodsNum)? onMinus;

  ///增加商品数量
  final Function(int goodsNum)? onAdd;

  ///最大值
  final int? max;

  ///增减商品数量
  const GoodsAddMinus(
      {super.key, this.num = 1, this.onMinus, this.onAdd, this.max = 999});

  @override
  State<StatefulWidget> createState() => _GoodsAddMinusState();
}

class _GoodsAddMinusState extends State<GoodsAddMinus> {
  int _goodsNum = 0;
  @override
  void initState() {
    super.initState();
    _goodsNum = widget.num;
  }
  
  @override
  void didUpdateWidget(covariant GoodsAddMinus oldWidget) {
    super.didUpdateWidget(oldWidget);
    _goodsNum = widget.num;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        BaseInteractive(
          childWidget: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Icon(
              Icons.remove,
              size: 16,
              color: Color(0xffaaaaaa),
            ),
          ),
          onClick: () {
            setState(() {
              if (_goodsNum > 1) {
                _goodsNum -= 1;
              }
              if (widget.onMinus != null) {
                widget.onMinus!(_goodsNum);
              }
            });
          },
        ),
        Container(
          alignment: Alignment.center,
          padding:
              EdgeInsets.only(left: 10.w, right: 10.w, top: 4.h, bottom: 4.h),
          decoration: BoxDecoration(
              color: Color(0xfff6f6f6),
              borderRadius: BorderRadius.all(Radius.circular(2))),
          margin: EdgeInsets.only(left: 5, right: 5),
          child: Text(
            '$_goodsNum',
            style: setTextStyle(10, FontWeight.w500, ThemeConfig.mainTextColor),
          ),
        ),
        BaseInteractive(
          childWidget: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Icon(
              Icons.add,
              size: 16,
              color: Color(0xffaaaaaa),
            ),
          ),
          onClick: () {
            if (_goodsNum >= widget.max!) {
              Tools.showToast("不能超过剩余库存");
              return;
            }
            setState(() {
              _goodsNum += 1;
            });
            if (widget.onAdd != null) {
              widget.onAdd!(_goodsNum);
            }
          },
        )
      ],
    );
  }
}
